<script>
import {Message} from "element-ui";

export default {
  data() {
    //表单验证（年龄）
    let checkAge = (rule, value, callback) => {
      if(value>150){
        callback(new Error('年龄输⼊过⼤'));
      }else{
        callback();
      }
    };
    //表单验证（账号唯一）
    let checkDuplicate =(rule,value,callback)=>{
      if(this.form.id){
        return callback();
      }
      this.$axios.get(this.$httpUrl +'/user/findByNo?no='+this.form.no).then(res=>res.data).then(res=>{
        if(res.code!=200){ //如果返回的不是200，查询失败，账号不存在，则可以添加
          callback()
        }else{
          callback(new Error('账号已经存在'));
        }
      })
    };

    return {
      tableData: [],
      pageSize: 10, //每页显示多少条
      pageNum: 1, //当前第几页
      total: 0, //总共多少条数据
      name: '',
      sex: '',
      sexs: [
        {
          value: '1',
          label: '男',
        },
        {
          value: '2',
          label: '女',
        }
      ],
      centerDialogVisible: false,//新增窗口默认不显示
      form: { //新增表单数据
        id: '',
        no: '',
        name: '',
        password: '',
        age: '',
        phone: '',
        sex: '1',
        roleId: '1' //角色id 默认为1，管理员
      },
      rules: { //表单验证规则
        no: [ //账号验证规则
          {required: true, message: '请输入账号', trigger: 'blur'},
          {min: 3, max: 8, message: '长度在3到8个字符', trigger: 'blur'},
          {validator: checkDuplicate, trigger: 'blur'}
        ],
        name: [ //姓名验证规则
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ],
        password: [ //密码验证规则
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 3, max: 8, message: '长度在3到8个字符', trigger: 'blur'},
        ],
        age: [
          {required: true, message: '请输⼊年龄', trigger: 'blur'},
          {min: 1, max: 3, message: '⻓度在 1 到 3 个位', trigger: 'blur'},
          {pattern: /^([1-9][0-9]*){1,3}$/,message: '年龄必须为正整数字',trigger: "blur"},
          {validator:checkAge,trigger: 'blur'}
        ],
        phone: [
          {required: true,message: "⼿机号不能为空",trigger: "blur"},
          {pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输⼊正确的⼿机号码", trigger:
                "blur"}
        ]
      },//表单验证规则
      noInput: false, //账号是否禁止输入  默认不禁止
    }
  },
  methods: {
        add() {  //新增按钮
          this.centerDialogVisible = true; //窗口打开
          this.$nextTick(() => { //页面渲染后执行,否则重置会报错
            this.resetForm(); //重置表单
            this.noInput = false; //账号允许输入
          })
        },
        resetForm() { //重置表单
          this.$refs.form.resetFields();
        },
        doSave() { //新增
          this.$axios.post(this.$httpUrl + '/user/save', this.form).then(res => res.data).then(res => {
            console.log(res)
            if (res.code == 200) {
              this.$message({
               message: '操作成功！',
               type: 'success'
             });
             this.centerDialogVisible = false //关闭窗口
             this.loadPost() //刷新页面
              this.resetForm()  //重置表单
            } else {
             this.$message({
                message: '操作失败！',
                type: 'error'
              });
           }
          })
         },
        doMod(){ //修改
          this.$axios.post(this.$httpUrl + '/user/update', this.form).then(res => res.data).then(res => {
            console.log(res)
            if (res.code === 200) {  //操作成功（弹窗）
              Message({
                message: '操作成功',
                type: 'success',
              });
              this.centerDialogVisible = false; //关闭窗口
              this.loadPost(); //刷新页面
            } else {
              Message.error('操作失败') //操作失败（弹窗）
            }
          })
        },
        save() {   //修改或新增
          this.$refs.form.validate((valid) => {
            if (valid) { //验证通过
              if (this.form.id) { //如果id存在，说明是修改，否则是新增
                this.doMod() //修改
              }else { //新增
                this.doSave();
              }
            } else { //验证失败
              console.log('error submit!!');
              return false;
            }
          });
        },
        del(id){ //删除
          console.log(id);

          this.$axios.get(this.$httpUrl + '/user/del?id='+id).then(res => res.data).then(res => {
            if (res.code === 200) {  //操作成功（弹窗）
              Message({
                message: '操作成功',
                type: 'success',
              });
              this.loadPost(); //刷新页面
            } else {
              Message.error('操作失败') //操作失败（弹窗）
            }
          })
        },
        mod(row){ //修改
          console.log(row);

          this.noInput=true; //账号禁止输入
          this.centerDialogVisible=true; //窗口打开

          this.$nextTick(() => { //页面渲染后执行
            this.form.id=row.id
            this.form.no=row.no
            this.form.name=row.name
            this.form.password=row.password
            this.form.sex=row.sex+''
            this.form.age=row.age+''
            this.form.phone=row.phone
            this.form.roleId=row.roleId
          })
        },
        handleSizeChange(val) { //每页显示条数
          console.log(`每页 ${val} 条`)
          this.pageNum = 1 //默认显示第一页
          this.pageSize = val
          this.loadPost()
        },
        handleCurrentChange(val) { //当前页
          console.log(`当前页: ${val}`)
          this.pageNum = val
          this.loadPost()
        },
        loadGet() { //查询测试
          this.$axios.get(this.$httpUrl + '/user/list').then(res => res.data).then(res => {
            console.log(res);
          })
        },
        loadPost() { //分页查询
          this.$axios.post(this.$httpUrl + '/user/listPageC1', {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            param: {
              name: this.name,
              sex: this.sex,
              roleId: '1'
            }
          }).then(res => res.data).then(res => {
            console.log(res);
            if (res.code === 200) {
              this.tableData = res.data;
              this.total = res.total;
            } else {
              alert("数据获取失败")
            }
          })
        },
        resetParam() {  //重置条件查询参数
          this.name = '';
          this.sex = '';
        },
  },
  beforeMount(){ //页面加载前执行
    this.loadPost();
  }
}
</script>


<template>
  <div>
    <div style="margin-bottom: 5px">
<!--      文本框，姓名搜索-->
      <el-input v-model="name" placeholder="请输入姓名"  style="width: 200px"
                @keyup.enter="loadPost">
      </el-input>
<!--      性别搜索+下拉列表-->
      <el-select
          v-model="sex"
          filterable
          placeholder="请选择性别"
          style="width: 240px;margin-left: 5px"
      >
        <el-option
            v-for="item in sexs"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        />
      </el-select>
      <el-button type="primary" style="margin-left: 5px" @click="loadPost" >查询</el-button>
      <el-button type="info" @click="resetParam">重置</el-button>
      <el-button type="success" style="margin-left: 5px" @click="add">新增</el-button>

    </div>
    <el-table :data="tableData"
              :header-cell-style="{ background:'#606266',color:'#ffffff'}"
              :cell-style="{background:'#f5f7fa'}"
              :row-style="{background:'#e9e9eb'}"
              border
              style="border-color: #dcdfe6"
    > //表格
      <el-table-column prop="id" label="ID" width="60"/>
      <el-table-column prop="no" label="账号" width="180"/>
      <el-table-column prop="name" label="姓名" width="180"/>
      <el-table-column prop="age" label="年龄" width="80"/>
      <el-table-column prop="sex" label="性别" width="80">
        <template #default="scope">
<!--          tag转换数据 1：男 2：女-->
          <el-tag
              :type="scope.row.sex === 1 ? 'primary' : 'danger'"
              disable-transitions
          >{{ scope.row.sex === 1 ? '男' : '女' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="roleId" label="角色" width="110">
        <template #default="scope">
<!--          tag转换数据 0：超级管理员 1：管理员 2：用户-->
          <el-tag
              :type="scope.row.roleId === 0 ? 'danger' : scope.row.roleId === 1 ? 'warning' : 'success'"
              disable-transitions
          >
            {{
              scope.row.roleId === 0 ? '超级管理员' :
                  scope.row.roleId === 1 ? '管理员' : '用户'
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="电话" width="120"/>
      <el-table-column prop="operate" label="操作">
        <template #default="scope">
          <el-button  type="primary" @click="mod(scope.row)">编辑</el-button>
          <el-popconfirm title="确定删除吗？" @confirm="del(scope.row.id)" >
            <template #reference>
              <el-button  type="danger" >删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
<!--     实现分页功能-->
    <el-pagination
        :current-page="pageNum"
        :page-size="pageSize"
        :page-sizes="[5,10, 20,30]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
    <el-dialog v-model="centerDialogVisible" title="提示" width="500" center>

      <el-form ref="form" :model="form" :rules="rules" label-width="auto" style="max-width: 600px">
        <el-form-item label="账号" prop="no" >
          <el-col :span="15">
<!--            账号，新增时可以修改 为false ;编辑时不可以  为true-->
            <el-input v-model="form.no"  :disabled="noInput"/>
          </el-col>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-col :span="15" >
            <el-input v-model="form.name"/>
          </el-col>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-col :span="15" >
            <el-input v-model="form.password"/>
          </el-col>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-col :span="15" >
            <el-input v-model="form.age"/>
          </el-col>
        </el-form-item>
        <el-form-item label="性别" >
          <el-radio-group v-model="form.sex">
            <el-radio value="1">男</el-radio>
            <el-radio value="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-col :span="15" >
            <el-input v-model="form.phone"/>
          </el-col>
        </el-form-item>
      </el-form>


      <template #footer>
        <div class="dialog-footer">
          <el-button @click="centerDialogVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="save">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>


</template>

<style scoped>
  div {
    margin: 0 !important;
    padding: 0 !important;
  }
  .el-container {
    margin: 0 !important;
    padding: 0 !important;
    border: none !important;
  }
  .el-menu {
    border-right: none !important;
  }
</style>